// the websocket and a standard server ip
sock = null;
wsuri = "ws://192.168.2.141:9000";


//player in the lobby
players = [];

// global variables for texts in the lobby
noPlayerConnected = "Es wird auf Spieler gewartet...";
kickPicture = "<img class='kick-thumb' alt='' src='images/Actions-im-kick-user-icon.png'>";

function init() {
	document.addEventListener("deviceready", onDeviceReady(), false);
}

/*
 * called as soon as 'deviceready' is fired
 */
function onDeviceReady(){
	// override the back-button functionality
	document.addEventListener("backbutton", function(){backKeyDown("listener");}, false);
	// the current html file, the js is executed
	htmlFile = null;
	// set to '1' if the 'kicked!'-message is received
	reasonkicked = 0;
	
	// listen to the 'pageshow'-event to act different on different html-page-initializations
	$(document).on('pageshow', function(e){
		// store the current loaded html-document name
		htmlFile = e.target.id+".html";
		// help-variable for console output
		var withh = "";
		
		if( htmlFile == "settings.html" ){
			refreshInputs(htmlFile);
			withh = " with "+volume+", "+vibration+", "+controls;
		}
		else if( htmlFile == "avatar.html" ){
			refreshInputs(htmlFile);
			withh = " with "+avatar+", "+name+", "+ip;
		}
		else if( (htmlFile == "controls.html") ){
			// control-initialization is now made in the moment the "GO"-message arrives
			
			// correct positioning of the control-divs
			/*	control-midpoints
			*		up		50.39 / 21.48	%
			*		down	50.39 / 76.56	%
			*		left	23.44 / 50.		%
			*		right	78.13 / 50.		% 
			*/
			
			// dynamic positioning of the div needed for the ontrols
			cross = document.getElementById("controls-cross");
			var up = document.getElementById("cross-up"),
				down = document.getElementById("cross-down"),
				left = document.getElementById("cross-left"),
				right = document.getElementById("cross-right");
			
			var crossPos = getPos(cross),
				crossWidth = cross.offsetWidth,
				crossHeight = cross.offsetHeight;
			
//			right.style.border = "1px solid blue";
//			up.style.border = "1px solid purple";
//			left.style.border = "1px solid gold";
//			down.style.border = "1px solid green";
			
			var helpDivSize = "5px";
			left.style.width = helpDivSize;
			left.style.height = helpDivSize;
			up.style.width = helpDivSize;
			up.style.height = helpDivSize;
			right.style.width = helpDivSize;
			right.style.height = helpDivSize;
			down.style.width = helpDivSize;
			down.style.height = helpDivSize;
			
			left.style.left = crossPos[0] + (0.5*crossWidth) + "px";
			left.style.top = crossPos[1] + (0.2344*crossHeight) + "px";
			up.style.left = crossPos[0] + (0.7656*crossWidth) + "px";
			up.style.top = crossPos[1] + (0.5039*crossHeight) + "px";
			right.style.left = crossPos[0] + (0.5*crossWidth) + "px";
			right.style.top = crossPos[1] + (0.7813*crossHeight) + "px";
			down.style.left = crossPos[0] + (0.2147*crossWidth) + "px";
			down.style.top = crossPos[1] + (0.5039*crossHeight) + "px";
		}
		else if( htmlFile == "lobby.html"){
			readSettings();
			displayPlayer();
			// initialize the touch-listener for kicks
		    document.addEventListener('touchstart', touchToKick, false);
		}
		else if( htmlFile == "connect.html" ){
			initWebsocket();
		}
		else if( htmlFile == "index.html"){
			// if user returns to the main-menu, the socket should be closed
			if(sock == null)
				console.log("sock is null");
			else{
				console.log("sock is running");
				sock.close();
			}
		}
		console.log("pageshow on "+htmlFile+withh);
		console.log("----------");
	});
	
	// console output for debugging
	$(document).on('pagehide', function(e){
		var htmlFile = e.target.id+".html";
		console.log("pagehide on "+htmlFile);
	});
	
	console.log("device completely ready!");
}

/*
 * this function is called as soon as the back-button is pressed
 */
function backKeyDown(source) {
	// extract the current html-document name if it isn't set before by 'pageshow'
	if( htmlFile == null ){
		htmlFile = window.location.pathname.split("/").reverse()[0];
	}
	
	var withh = "";
	// if back is pressed in the main menu, simply exit the app
	if(htmlFile == "index.html"){
		console.log("exit...");
		navigator.app.exitApp();
	}
	else{
		// on the settings- and avatar-page get the settings out of the inputs and save them
		if(htmlFile == "settings.html"){
			var val = $("#volume-slider").val() +"#"+ $("#vibration-switch").val() +"#"+ $("#control-switch").val() +"#"+ avatar +"#"+ name +"#"+ ip;
			
			withh = " with "+ $("#volume-slider").val() +", "+ $("#vibration-switch").val() +", "+ $("#control-switch").val();
			window.MyClass.writeSharedPrefs(val);
		}
		else if(htmlFile == "avatar.html"){
			// check if client name is valid
			var n = ($("#name-input").val());
			var t = /\W/.test(n);
			if( t || n.length < 1){
				navigator.notification.alert("Name darf nur Kleinbuchstaben, GroÃŸbuchstaben und Zahlen enthalten und muss mindestens ein Zeichen lang sein!");
				return;
			}
			var av = $("#control-group :radio:checked").val();
			// check if ip-input is a valid ip
			var i = ($("#ip-input").val());
			var be = i.split(":");
			if(be.length != 2){
				navigator.notification.alert("Server-Ip stimmt nicht mit 'ip:port' Ã¼berein!");//, null, "TITÃ„L");
				return;
			}
			var a = be[0].split(".");
			if( a.length != 4){
				navigator.notification.alert("Der Server-Ip IP-Teil hat ein falsches Format!");
				return;
			}
			var b = a[1],
				c = a[2],
				d = a[3],
				a = a[0];
			var af = be[1];
			if( !(	(/\d+/.test(a))
				&&	(/\d+/.test(b))
				&&	(/\d+/.test(c))
				&&	(/\d+/.test(d))
				&&	(/\d+/.test(af))
				)){
				navigator.notification.alert("IP und Port dÃ¼rfen nur aus Zahlen bestehen!");
				return;
			}
			var val = volume +"#"+ vibration +"#"+ controls +"#"+ (av) +"#"+ (n) +"#"+ (i);
			withh = " with "+(av) +", "+ (n) +", "+ (i);
			window.MyClass.writeSharedPrefs(val);
		}
		// on controls-page, ask if user is sure about his leaving
		else if( (htmlFile == "controls.html") ){
			buttons = ["Nein", "Ja"];
			if( source == "listener" ){
				navigator.notification.confirm("Wirklich verlassen?", function(i){controlsBack(i);}, "Verlassen", buttons);
				return;
			}
			else{
				controlsBack(2);
				return;
			}
		}
		// enable the kick-user touch listener
		else if(htmlFile == "lobby.html"){
		    document.removeEventListener('touchstart', touchToKick, false);
		}
		
		// back is different from lobby and connect
		console.log("move back on "+htmlFile+withh);
		if(htmlFile == "lobby.html" || htmlFile == "connect.html")// || htmlFile == "controls.html")
			loadIndex();
		else
			navigator.app.backHistory();
	}
}
/*
 * realizes the confirmation for back-pressed in the controls
 */
function controlsBack(i){
	console.log("button pressed: "+i+" - "+buttons[i-1]);
	// dismiss confirmation with back-key -> i=0
	// pressed Nein -> i=1
	//pressed Ja -> i=2
	// when the dialog is dismissed without a button press or "Nein" is pressed
	if( (i == 0) || (i == 1) )
			return;

	if(controls == "off"){
		navigator.accelerometer.clearWatch(watchID);
		disableBombListener();
	}
	else{
		disableControlsListeners();
	}
	console.log("move back on "+htmlFile);
	loadIndex();
}

/*
 * the load...() methods are for loading the pages
 */
function loadIndex(){
	$.mobile.changePage("index.html");//, { transition: "slide" });
}

function loadSettings(){
	readSettings();
	$.mobile.changePage("settings.html", { transition: "slide" });
}

function loadManual(){
	$.mobile.changePage("manual.html", { transition: "slide" });
}

function loadAvatar(){
	readSettings();
	$.mobile.changePage("avatar.html", { transition: "slide" });
}

function loadConnect(){
	readSettings();
	$.mobile.changePage("connect.html", { transition: "slide", changeHash: false });
}

function loadLobby(){
	$.mobile.changePage("lobby.html", { transition: "slide", changeHash: false });
}

/*
 * called as soon as the websocket is connected
 */
function connected(){
	var a = 1;
	if(avatar == "char02")
		a = 2;
	websocketSend("Hello Server!"+name+"#"+a);
}

function loadControls(){
	readSettings();
	$.mobile.changePage("controls.html", { transition: "slide", changeHash: false });
}

/*
 * for scanning the server-ip
 */
function scanQR(){
	window.plugins.barcodeScanner.scan( function(result) {
		if( result.cancelled == true)
			return;
		var buttons = ["Nein", "Ja"];
		navigator.notification.confirm("Ist '"+ result.text +"' korrekt?", function(i){
			console.log("button pressed: "+i+" - "+buttons[i-1]);
			// when the dialog is dismissed without a button press or "Nein" is pressed
			if( (i == 0) || (i == 1) )
					return;
			
			$("#ip-input").val(result.text);
		}, "Server-IP", buttons);
    }, function(error) {
    	navigator.notification.alert("Scanning failed: " + error);
                }
    );
}

/*
 * configures the player-div on loading of the lobby
 */
function displayPlayer(){
	var playa = localStorage.player1;
	if(playa != null && playa != "null" && playa != ""){
		clientName = playa;
        
        playa = localStorage.player2;
        if(playa != null && playa != "null" && playa != ""){
    		addPlayer(playa);
            
            playa = localStorage.player3;
            if(playa != null && playa != "null" && playa != ""){
        		addPlayer(playa);
                
                playa = localStorage.player4;
                if(playa != null && playa != "null" && playa != ""){
            		addPlayer(playa);
            	}
        	}
    	}
        else{
        	document.getElementById("noplayer").innerHTML = noPlayerConnected;
        }
	}
}

/*
 * takes the next empty player-div and puts the new player into it
 */
function addPlayer(name){
	//noPlayerConnected;
	var noPlayer = document.getElementById("noplayer"),
		player1 = document.getElementById("player1"),
		player2 = document.getElementById("player2"),
		player3 = document.getElementById("player3");
	
	if( player1.innerHTML.trim() == "" ){
		noPlayer.innerHTML = "";
		player1.innerHTML = name + kickPicture;
		player1.style.listStyleType = "circle";
	}
	else if( player2.innerHTML.trim() == "" ){
		player2.innerHTML = name + kickPicture;
		player2.style.listStyleType = "circle";
	}
	else if( player3.innerHTML.trim() == "" ){
		player3.innerHTML = name + kickPicture;
		player3.style.listStyleType = "circle";
	}
}
/*
 * takes the next player-div containing the given player name and removes the player out of it
 */
function removePlayer(name){
	var noPlayer = document.getElementById("noplayer"),
		player1 = document.getElementById("player1"),
		player2 = document.getElementById("player2"),
		player3 = document.getElementById("player3");
	
	if( player1.innerHTML.split("<")[0] == name ){
		player1.innerHTML = player2.innerHTML;
		player2.innerHTML = player3.innerHTML;
		player3.innerHTML = "";
		
		if( player1.innerHTML.trim() == ""){
			noPlayer.innerHTML = noPlayerConnected;
		}
	}
	else if( player2.innerHTML.split("<")[0] == name ){
		player2.innerHTML = player3.innerHTML;
		player3.innerHTML = "";
	}
	else if( player3.innerHTML.split("<")[0] == name ){
		player3.innerHTML = "";
	}
	
	if( player1.innerHTML.trim() == "")
		player1.style.listStyleType = "none";
	if( player2.innerHTML.trim() == "")
		player2.style.listStyleType = "none";
	if( player3.innerHTML.trim() == "")
		player3.style.listStyleType = "none";
}

/*
 * called in the moment the user touches the lobby screen
 */
function touchToKick(event){
	// if clicked element is an image
	if(event.target instanceof HTMLImageElement){
		var img = event.target,
			li = img.parentElement;
		//if parent-element of the clicked element is an li-element
		if(li.className == "player"){
			var name = li.innerHTML.split("<")[0];
			
			var b = img.src.split("-");
			b = b[b.length-1];
			if(b != "icon_clicked.png"){
				//send kick-vote-information to server
				if(websocketSend("Vote Kick!"+name)){
					//change image
					img.src = "images/Actions-im-kick-user-icon_clicked.png";
				}
			}
		}
	}
}

/* avatar.html */
/*
 * enables automatic refresh of the radioboxes on the avatar page
 */
$(".radio_button").change(checkIncrement);
function checkIncrement(){
	$('input:[name=radiob]:radio:checked').checkboxradio("refresh");
	rd=$('input:[name=radiob]:radio:checked').val();
	inc="i"+rd;
	var ch=1;
	var sl=parseInt(rd)+parseInt(ch);
	$("#slider").attr("min", sl).slider("refresh");   
}

/* controls.html */
/*
 * initialize the touch listeners for the touch-controls
 */
function initControlsListeners(){
	localTouches = [null, null, null, null];	// 0 for up; 1 for down; 2 for left; 2 for right
    document.addEventListener('touchstart', touch_down, false);
    document.addEventListener('touchend', touch_up, false);
	console.log("initialized controls-listeners");
}
/*
 * deactivate the touch listeners for the touch-controls
 */
function disableControlsListeners(){
	document.removeEventListener('touchstart', touch_down, false);
	document.removeEventListener('touchend', touch_up, false);
	console.log("removed controls-listeners");
}

/*
 * compute the position of and html-div-element
 */
function getPos(obj){
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
		return [curleft,curtop];
	}
}
/*
 * the nearlyEqual-methods support the recoginition of the correct touch positions
 */
function nearlyEqual(a, b){
	var t = 20;
	var al = a-t,
		ag = a+t;
	if(al < b  && b < ag)
		return true;
	else
		return false;
}
function vectorNearlyEqual(a, b){
	var t1 = nearlyEqual(a[0], b[0]),
		t2 = nearlyEqual(a[1], b[1]);
	return (t1 && t2);
}
function containsNearlyEqualVector(list, v){
	var e = null;
	for( var i=0; i<list.length; i++){
		e = list[i];
		if(e != null && vectorNearlyEqual(v, e))
			return new Array(i, e);
	}
	return new Array(-1, null);
}

/*
 * for the touch-controls touch listener
 */
function touch_down(event){
	// if the bomb is touched
	if( event.target.id == "controls-bomb" ){
		plantBomb();
		bomb = 1;
		document.getElementById("controls-bomb").src = "images/bomb3.png";
	}
	else{
		// identify and save new touches
		var newTouches = new Array();
		var t = null;
		for( var i=0; i<event.touches.length; i++ ){
			// only the position of the touch is necessary
			t = [event.touches[i].pageX , event.touches[i].pageY];
			// remember it if there isn't already a touch around this position
			if(containsNearlyEqualVector(localTouches, t)[0] == -1){	// somewhat like if( localTouches.indexOf(lt) == -1 )
				newTouches.push(t);
			}
		}
		
		// print the new touches
		var str = "";
		for(var i=0; i<newTouches.length; i++)
			str += "["+newTouches[i]+"]"+ (i==0 ? "" : ", ");
		console.log("touches down "+str);
		
		// print a warning if this unlikely case happens 
		if(newTouches.length > 1)
			console.log("MORE THEN ONE NEW TOUCH!");
		
		cross = document.getElementById("controls-cross");
		
		var upCross = getPos(document.getElementById("cross-up"));
		var downCross = getPos(document.getElementById("cross-down"));
		var leftCross = getPos(document.getElementById("cross-left"));
		var rightCross = getPos(document.getElementById("cross-right"));
			
		var touch = newTouches[0];
		
		var upDis = Math.sqrt( Math.pow(touch[0]-upCross[0], 2) + Math.pow(touch[1]-upCross[1], 2) );
		var downDis = Math.sqrt( Math.pow(touch[0]-downCross[0], 2) + Math.pow(touch[1]-downCross[1], 2) );
		var leftDis = Math.sqrt( Math.pow(touch[0]-leftCross[0], 2) + Math.pow(touch[1]-leftCross[1], 2) );
		var rightDis = Math.sqrt( Math.pow(touch[0]-rightCross[0], 2) + Math.pow(touch[1]-rightCross[1], 2) );
			
		var minDis = Math.min(upDis, Math.min(downDis, Math.min(leftDis, rightDis)));
		
		switch(minDis){
		case upDis:
			localTouches[0] = t;
			up = 1;
			if(left == 1) cross.src = "images/controls/up-left.png";
			else if (right == 1) cross.src = "images/controls/up-right.png";
			else{
				if(down == 1){
					moveDownEnd();
					down = 0;
				}
				cross.src = "images/controls/up.png";
			}
			moveUp();
			break;
		case downDis:
			localTouches[1] = t;
			down = 1;
			if(left == 1) cross.src = "images/controls/down-left.png";
			else if (right == 1) cross.src = "images/controls/down-right.png";
			else{
				if(up == 1){
					moveUpEnd();
					up = 0;
				}
				cross.src = "images/controls/down.png";
			}
			moveDown();
			break;
		case leftDis:
			localTouches[2] = t;
			left = 1;
			if(down == 1) cross.src = "images/controls/down-left.png";
			else if (up == 1) cross.src = "images/controls/up-left.png";
			else{
				if(right == 1){
					moveRightEnd();
					right = 0;
				}
				cross.src = "images/controls/left.png";
			}
			moveLeft();
			break;
		case rightDis:
			localTouches[3] = t;
			right = 1;
			if(down == 1) cross.src = "images/controls/down-right.png";
			else if (up == 1) cross.src = "images/controls/up-right.png";
			else{
				if(left == 1){
					moveLeftEnd();
					left = 0;
				}
				cross.src = "images/controls/right.png";
			}
			moveRight();
			break;
		default: break;
		}
	}
}
/*
 * for the touch-controls touch listener
 */
function touch_up(event){
	if(event.target.id == "controls-bomb"){
		plantBombEnd();
		bomb = 0;
		document.getElementById("controls-bomb").src = "images/bomb.png";
	}
	else{
		// convert event.touches to a list of positions
		var eventTouches = new Array();
		for(var v=0; v<event.touches.length; v++){
			eventTouches.push( [event.touches[v].pageX, event.touches[v].pageY] );
		}
		
		// detect which touch are ended and remove them from the local list
		var deleted = [null, null, null, null];
		var lt = null;
		for( var i=0; i<localTouches.length; i++ ){
			lt = localTouches[i];
			if( lt != null && containsNearlyEqualVector(eventTouches, lt)[0] == -1){	// somewhat like if( eventTouches.indexOf(lt) == -1 )
				deleted[i] = lt;
				localTouches[i] = null;
			}
		}

		// print the ended touches
		var str = "touches up ";
		var dd = null;
		for( var d=0; d<deleted.length; d++){
			dd = deleted[d];
			if(dd != null)
			str += d+".["+dd+"], ";
		}
		console.log(str);
		
		var t = null;
		var err = 0;
		cross = document.getElementById("controls-cross");
		for( var i=0; i<deleted.length; i++){
			t = deleted[i];
			if( t == null) 
				continue;
			
			console.log("arrived!");
			
			err++;
			switch( i ){
				case 0:
					if(up == 0)
						break;
					moveUpEnd();
					up = 0;
					if(left == 1) cross.src = "images/controls/left.png";
					else if(right == 1) cross.src = "images/controls/right.png";
					else cross.src = "images/controls/default.png";
					break;
				case 1:
					if(down == 0)
						break;
					moveDownEnd();
					down = 0;
					if(left == 1) cross.src = "images/controls/left.png";
					else if(right == 1) cross.src = "images/controls/right.png";
					else cross.src = "images/controls/default.png";
					break;
				case 2:
					if(left == 0)
						break;
					moveLeftEnd();
					left = 0;
					if(down == 1) cross.src = "images/controls/down.png";
					else if(up == 1) cross.src = "images/controls/up.png";
					else cross.src = "images/controls/default.png";
					break;
				case 3:
					if(right == 0)
						break;
					moveRightEnd();
					right = 0;
					if(down == 1) cross.src = "images/controls/down.png";
					else if(up == 1) cross.src = "images/controls/up.png";
					else cross.src = "images/controls/default.png";
					break;
				default: break;
			}
		}
		// print a warning if this unlikely case happens 
		if(err > 1)
			console.log("MORE THEN ONE DELETED TOUCH!");
	}
}

/*
 * for the accelerometer-controls bomb-touch listener
 */
function initilizeBombListener(){
    document.addEventListener('touchstart', touch_bomb, false);
    document.addEventListener('touchend', touch_bomb_end, false);
}
/*
 * for the accelerometer-controls bomb-touch listener
 */
function disableBombListener(){
    document.removeEventListener('touchstart', touch_bomb, false);
    document.removeEventListener('touchend', touch_bomb_end, false);
}

/*
 * called from the accelerometer watching
 */
function accelerometerOnSuccess(acceleration){
	if(acceleration.x == null || acceleration.y == null)
		return;

	bomb = document.getElementById("controls-bomb");
	cross = document.getElementById("controls-cross");
	
	var x = acceleration.x,
		y = acceleration.y;

	// x is up-down
	if(x > downLimit){
		if(down == 0){
			moveDown();
			console.log("move down");
			down = 1;
			if(left == 1) cross.src = "images/controls/down-left.png";
			else if (right == 1) cross.src = "images/controls/down-right.png";
			else cross.src = "images/controls/down.png";
		}
	}
	else if(x < upLimit){
		if(up == 0){
			moveUp();
			up = 1;
			if(left == 1) cross.src = "images/controls/up-left.png";
			else if (right == 1) cross.src = "images/controls/up-right.png";
			else cross.src = "images/controls/up.png";
		}
	}
	else{
		if(up == 1){
			moveUpEnd();
			up = 0;
			if(left == 1) cross.src = "images/controls/left.png";
			else if(right == 1) cross.src = "images/controls/right.png";
			else cross.src = "images/controls/default.png";
		}
		if(down == 1){
			moveDownEnd();
			down = 0;
			if(left == 1) cross.src = "images/controls/left.png";
			else if(right == 1) cross.src = "images/controls/right.png";
			else cross.src = "images/controls/default.png";
		}
	}
	
	// y is left-right
	if(y > rightLimit){
		if(right == 0){
			moveRight();
			right = 1;
			if(down == 1) cross.src = "images/controls/down-right.png";
			else if (up == 1) cross.src = "images/controls/up-right.png";
			else cross.src = "images/controls/right.png";
		}
	}
	else if(y < leftLimit){
		if(left == 0){
			moveLeft();
			left = 1;
			if(down == 1) cross.src = "images/controls/down-left.png";
			else if (up == 1) cross.src = "images/controls/up-left.png";
			else cross.src = "images/controls/left.png";
		}
	}
	else{
		if(left == 1){
			moveLeftEnd();
			left = 0;
			if(down == 1) cross.src = "images/controls/down.png";
			else if(up == 1) cross.src = "images/controls/up.png";
			else cross.src = "images/controls/default.png";
		}
		if(right == 1){
			moveRightEnd();
			right = 0;
			if(down == 1) cross.src = "images/controls/down.png";
			else if(up == 1) cross.src = "images/controls/up.png";
			else cross.src = "images/controls/default.png";
		}
	}
}

/*
 * called if display is touched in the accelerometer-controls
 */
function touch_bomb(){
	plantBomb();
	bomb = 1;
	bombIcon = document.getElementById("controls-bomb");
	bombIcon.src = "images/bomb3.png";
}
/*
 * called if display is touched in the accelerometer-controls
 */
function touch_bomb_end(){
	plantBombEnd();
	bomb = 0;
	bombIcon = document.getElementById("controls-bomb");
	bombIcon.src = "images/bomb.png";
}

/*
 * simply make and console output if accelerometer-data couldn't be read
 */
function accelerometerOnError(){
	console.log("couldnt read accelerometer");
}

/* settings.html and avatar.html */
volume = -1;
vibration = -1;
controls = -1;
avatar = -1;
name = -1;

/*
 * read the shared preference with the help of the java class
 */
function readSettings(){
	var content = window.MyClass.readSharedPrefs();
	content = content.split("#");
	volume = content[0];
	vibration = content[1];
	controls = content[2];
	avatar = content[3];
	name = content[4];
	ip = content[5];
}

/*
 * refresh the input-fields depending on which page is loaded
 */
function refreshInputs(page){
	if(page == "settings.html"){
		var slider = $("#volume-slider");
		slider.val(parseInt(volume)).slider("refresh");
	    
	    var vibrationswitch = $("#vibration-switch");
	    vibrationswitch.val(vibration).slider('refresh');
	
	    var controlsswitch = $("#control-switch");
	    controlsswitch.val(controls).slider('refresh');
	}
	else if(page == "avatar.html"){
		$("#name-input").val(name);
		$("#ip-input").val(ip);
		if(avatar == "char01"){
			$("#radio-choice-1").attr("checked", true).checkboxradio("refresh");
			$("#radio-choice-2").attr("checked", false).checkboxradio("refresh");
		}
		else if(avatar == "char02"){
			$("#radio-choice-1").attr("checked", false).checkboxradio("refresh");
			$("#radio-choice-2").attr("checked", true).checkboxradio("refresh");
		}
		else{
			
		}
	}
}

/* websocket */

/*
 * initialize the websocket
 */
function initWebsocket() {
	wsuri = "ws://"+ ip;
	sock = new WebSocket(wsuri);
	sock.onopen = function () {
		console.log("connected to " + wsuri);
		connected();
		socketClosed = 0;
	};
	// distinguish from getting kicked and connection loss
	sock.onclose = function (e) {
		console.log("socket-connection closed(" + e.code + ")");
		if( htmlFile == "index.html"){
			// game left normally
			return;
		}
		else if( reasonkicked == 1 ){
			navigator.notification.alert("Du wurdest gekickt!");
		}
		else{
			navigator.notification.alert("Verbindung zum Server verloren!");
		}
		window.setTimeout("backKeyDown('onclose')", 1000);
	};
	// extract command and parameters from the message and react accordingly
	sock.onmessage = function (e) {
		if( htmlFile == "index.html")
			return;
		console.log("message received: " + e.data);
		var parts = e.data.split("!");
		var command = parts[0],
			parameter = parts[1];
		if(command == "Hello Client"){
			clientName = null;
			players = [null, null, null];
			if(parameter.length > 1){
				clientName = parameter.split("&");
				if(clientName.length > 1){
					var playas = clientName[1].split("#");
					clientName = clientName[0];
					for(var i=0; i<playas.length; i++){
						players[i] = playas[i];
					}
				}
			}
			localStorage.player1 = clientName;
			localStorage.player2 = players[0];
			localStorage.player3 = players[1];
			localStorage.player4 = players[2];
			loadLobby();
		}
		else if(command == "start"){
			loadControls();
		}
		else if( command == "GO"){
			bomb = 0;
			up = 0;
			down = 0;
			left = 0;
			right = 0;
			if(controls == "off"){
				downLimit = 3;
				upLimit = -3;
				leftLimit = -2.5;
				rightLimit = 2.5;
			    var options = { frequency: 250 };
				watchID = navigator.accelerometer.watchAcceleration(accelerometerOnSuccess, accelerometerOnError, options);
				initilizeBombListener();
			}
			else
				initControlsListeners();
		}
		else if(command == "New Player"){
			if(parameter != clientName)
				addPlayer(parameter);
		}
		else if(command == "Player left"){
			removePlayer(parameter);
		}
		else if(command == "kicked"){
			reasonkicked = 1;
		}
		else if(command == "Stop"){
			backKeyDown('stop');
		}
		else if( command == "sudden_death"){
			console.log("sudden");
			if( vibration == "on"){
				window.setTimeout("navigator.notification.vibrate(200)", 0);
				window.setTimeout("navigator.notification.vibrate(200)", 400);
				window.setTimeout("navigator.notification.vibrate(200)", 800);
			}
		}
		else if( command == "upgrade_collected"){
			console.log("upgrade");
			if( vibration == "on"){
				window.setTimeout("navigator.notification.vibrate(700)", 0);
			}
		}
		else if( command == "bomb_placed"){
			console.log("placed");
			if( vibration == "on"){
				window.setTimeout("navigator.notification.vibrate(200)", 0);
			}
		}
		else if( command == "client_death"){
			console.log("death");
			if( vibration == "on"){
				window.setTimeout("navigator.notification.vibrate(700)", 0);
				window.setTimeout("navigator.notification.vibrate(700)", 1000);
				window.setTimeout("navigator.notification.vibrate(700)", 2000);
			}
			backKeyDown("death");
		}
		else
			console.log("unknown message received");
	};
}

/*
 * sends messages via the websocket
 */
function websocketSend(msg){
	if(sock.readyState == 1){
		sock.send(msg);
		console.log("message sent "+msg);
		return 1;
	}
	else{
		console.log("socket not connected");
		return 0;
	}
}

/*
 * these move...()-methods are called as soon as a touch for the action is recognized
 */
function moveUp(){
//	console.log("move up");
	websocketSend("kd!t");
}
function moveDown(){
//	console.log("move down");
	websocketSend("kd!b");
}
function moveLeft(){
//	console.log("move left");
	websocketSend("kd!l");
}
function moveRight(){
//	console.log("move right");
	websocketSend("kd!r");
}
function plantBomb(){
//	console.log("plant Bomb");
	websocketSend("kd!bomb");
}

function moveUpEnd(){
//	console.log("end move up");
	websocketSend("ku!t");
}
function moveDownEnd(){
//	console.log("end move down");
	websocketSend("ku!b");
}
function moveLeftEnd(){
//	console.log("end move left");
	websocketSend("ku!l");
}
function moveRightEnd(){
//	console.log("end move right");
	websocketSend("ku!r");
}
function plantBombEnd(){
	// no effect on server
	// console.log("end plant Bomb");
}